﻿using System;
using System.Reflection;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Windows.UI;

namespace Windows8Accelerator.Core.Xaml.Helpers
{
    public static class ColorHelperEx
    {
        public static Color StringToColor(string color)
        {
            if (color.StartsWith("#"))
            {
                var alphaStart = (color.Length == 9) ? 1 : -1;
                var redStart = alphaStart + 2;
                var greenStart = redStart + 2;
                var blueStart = greenStart + 2;
                byte alpha = 255, red, green, blue;
                if (alphaStart > 0)
                    alpha = byte.Parse(color.Substring(alphaStart, 2), System.Globalization.NumberStyles.HexNumber);
                red = byte.Parse(color.Substring(redStart, 2), System.Globalization.NumberStyles.HexNumber);
                green = byte.Parse(color.Substring(greenStart, 2), System.Globalization.NumberStyles.HexNumber);
                blue = byte.Parse(color.Substring(blueStart, 2), System.Globalization.NumberStyles.HexNumber);
                return Color.FromArgb(alpha, red, green, blue);
            }

            var property = typeof(Colors).GetRuntimeProperty(color);
            if (property != null)
                return ((Color)property.GetValue(null));

            return default(Color);
        }

        public static string ColorToString(Color color)
        {
            return String.Format("#{0:x2}{0:x2}{0:x2}{0:x2}", color.A, color.R, color.G, color.B);
        }
    }
}
